import os
import shutil
import sys
import time
import threading
import queue
from time import sleep

from pyJianYingDraft import Export_resolution, Export_framerate
from src.router.render import status_manager
from src.service.save_draft import save_draft_impl
from src.utils.logger import get_logger
from src.utils.oss import upload_to_oss
from src.utils.timehelper import TimeHelper
import pyJianYingDraft as draft
import config
# 如果是Linux系统，则不导入uiautomation，并避免执行相关代码
if sys.platform.startswith('win'):
    from uiautomation import UIAutomationInitializerInThread
else:
    # 可以在这里定义一个假的UIAutomationInitializerInThread类或设置一个标记
    # 或者直接跳过，并在使用的地方做判断
    UIAutomationInitializerInThread = None
    # 或者使用其他替代方案（如果有的话）或者只是pass

logger = get_logger("capcut")

class AsyncVideoProcessor:
    """异步视频处理器，封装视频导出和上传功能"""

    def __init__(self, status_manager):
        """初始化视频处理器"""
        self.status_manager = status_manager

    def run(self, task_id: str, draft_id: str,
            resolution: Export_resolution = Export_resolution.RES_1080P,
            framerate: Export_framerate = Export_framerate.FR_30) -> None:
        """运行视频处理任务"""
        output_file = f"{draft_id}_{TimeHelper.timestamp()}_output.mp4"
        output_path = os.path.join(config.DRAFT_DIR, output_file)

        try:
            # 执行视频导出（优化重点）
            self._export_video(draft_id, output_path, task_id, resolution, framerate)

        except Exception as e:
            error_msg = str(e)
            logger.error(f"任务处理失败: task_id={task_id}, error={error_msg}")
            # 更新任务状态：处理失败
            self.status_manager.update_task_status(
                task_id,
                status=self.status_manager.STATUS_FAILED,
                message=f"处理失败: {error_msg}",
                error=error_msg
            )

    def _export_video(self, draft_id: str, output_path: str, task_id: str, resolution: Export_resolution,
                      framerate: Export_framerate) -> None:
        """导出视频（优化版：添加进度监控）"""
        try:
            self.status_manager.update_task_status(
                task_id, status=self.status_manager.STATUS_PROCESSING,
                progress='0', message='正在下载草稿及素材'
            )
            # 保存草稿
            save_draft_impl(draft_id, config.DRAFT_DIR, False)
            sleep(1)
            # 在UI自动化上下文中执行导出
            with UIAutomationInitializerInThread():
                ctrl = draft.Jianying_controller()
                # 执行导出
                ctrl.export_draft(
                    draft_id, output_path,
                    resolution=resolution,  # 传递枚举值字符串
                    framerate=framerate,  # 传递枚举值字符串
                    task_id=task_id
                )
            # export_thread = threading.Thread(
            #     target=self.export_draft_in_thread,
            #     args=(draft_id, output_path, resolution, framerate, task_id),
            #     name=f"ExportThread-{task_id}"
            # )
            # export_thread.daemon = True  # 设置为守护线程，主程序退出时自动结束
            # export_thread.start()

        except Exception as e:
            logger.error(f"视频导出失败: {str(e)}")
            self.status_manager.update_task_status(
                task_id, status=self.status_manager.STATUS_FAILED,
                message=f"视频导出失败: {str(e)}", error=str(e)
            )
            raise


